from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from appi.apps.utils.data_base_config import Base






class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True,index=True)
    name = Column(String, nullable=False,index=True)
    password = Column(String, nullable=False)
    age = Column(Integer, nullable=False)

    def to_dict(self):
        return {
            'id':self.id,
            'name':self.name,
            'age':self.age
        }

print("User 已准备！")




class UserMapper:
    def __init__(self):
        from appi.apps import data_session
        self.db = data_session()

    def add_user(self,name,password,age) -> User:
        user = User(name=name,password=password,age=age)
        self.db.add(user)
        self.db.commit()
        self.db.refresh(user)
        return user

    def get_user(self,id):
        user = self.db.query(User).filter(User.id==id).first()
        return user

    def get_all_users(self):
        users = self.db.query(User).all()
        return users

    def update_user(self,id,name,age):
        user = self.db.query(User).filter(User.id==id).first()
        user.name = name
        user.age = age
        self.db.commit()
        return user

    def delete_user(self,id):
        user = self.db.query(User).filter(User.id==id).first()
        self.db.delete(user)
        self.db.commit()
        return user